﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;
using System.ComponentModel;
using System.Reactive.Linq;

namespace Property
{
    /// <summary>
    /// Contains words that can be applied to property instances. 
    /// </summary>
    public static class PropertyExtensionsReactive
    {
        /// <summary>
        /// <para>Unfold the property's Value into an observable sequence.</para>
        /// <para>Causes no side effects.</para>
        /// </summary>
        public static IObservable<T> ToObservable<T>(this IProperty<T> source)
        {
            if (source == null) throw new ArgumentNullException("source");

            return Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                handler => handler.Invoke, h => source.PropertyChanged += h, h => source.PropertyChanged -= h)
                .Where(o => o.EventArgs.PropertyName == "Value").Select(o => source.DebugValue).Publish().RefCount();
        }
    }
}
